﻿using RestSharp;
using RestSharp.Authenticators;
using System.Net.Http;
using System.Text.Json;

namespace YourNamespace.Http
{
    /// <summary>
    /// 基于RestSharp的HTTP客户端封装
    /// </summary>
    public class HttpRestClient : IDisposable
    {
        private readonly RestClient _client;
        private readonly JsonSerializerOptions _jsonOptions;

        ///// <summary>
        ///// 构造函数（自定义RestClientOptions）
        ///// </summary>
        ///// <param name="baseUrl">API基地址</param>
        ///// <param name="timeout">超时时间（毫秒）</param>
        ///// <param name="jsonOptions">JSON序列化选项</param>
        //public HttpRestClient(string baseUrl, int timeout = 30000, JsonSerializerOptions jsonOptions = null)
        //{
        //    var options = new RestClient(baseUrl)
        //    {
        //        MaxTimeout = timeout,
        //        ThrowOnAnyError = false // 手动处理错误
        //    };

        //    _client = new RestClient(options);
        //    _jsonOptions = jsonOptions ?? new JsonSerializerOptions
        //    {
        //        PropertyNameCaseInsensitive = true,
        //        WriteIndented = false
        //    };

        //    // 配置JSON序列化
        //    _client.UseSystemTextJson(_jsonOptions);
        //}

        /// <summary>
        /// 设置认证（如JWT、Basic Auth）
        /// </summary>
        public void SetAuthenticator(IAuthenticator authenticator)
        {
            _client.Authenticator = authenticator;
        }

        /// <summary>
        /// 发送GET请求
        /// </summary>
        public async Task<T> GetAsync<T>(string resource, Dictionary<string, object> queryParams = null, Dictionary<string, string> headers = null)
        {
            var request = new RestRequest(resource, Method.GET);
            AddParameters(request, queryParams, headers);
            return await ExecuteAsync<T>(request);
        }

        /// <summary>
        /// 发送POST请求
        /// </summary>
        public async Task<TResponse> PostAsync<TRequest, TResponse>(string resource, TRequest body, Dictionary<string, string> headers = null)
        {
            var request = new RestRequest(resource, Method.POST);
            AddHeaders(request, headers);
            request.AddJsonBody(body);
            return await ExecuteAsync<TResponse>(request);
        }

        /// <summary>
        /// 发送PUT请求
        /// </summary>
        public async Task<TResponse> PutAsync<TRequest, TResponse>(string resource, TRequest body, Dictionary<string, string> headers = null)
        {
            var request = new RestRequest(resource, Method.PUT);
            AddHeaders(request, headers);
            request.AddJsonBody(body);
            return await ExecuteAsync<TResponse>(request);
        }

        /// <summary>
        /// 发送DELETE请求
        /// </summary>
        public async Task<T> DeleteAsync<T>(string resource, Dictionary<string, object> queryParams = null, Dictionary<string, string> headers = null)
        {
            var request = new RestRequest(resource, Method.DELETE);
            AddParameters(request, queryParams, headers);
            return await ExecuteAsync<T>(request);
        }

        /// <summary>
        /// 通用执行方法
        /// </summary>
        private async Task<T> ExecuteAsync<T>(RestRequest request)
        {
            var response = await _client.ExecuteAsync<T>(request);


            if (!response.IsSuccessful || response.ErrorException != null)
            {
                throw new HttpRequestException(
                    $"HTTP请求失败: {response.StatusCode} - {response.ErrorMessage}",
                    response.ErrorException);
            }

            return response.Data;
        }

        /// <summary>
        /// 添加请求头和查询参数
        /// </summary>
        private void AddParameters(RestRequest request, Dictionary<string, object> queryParams, Dictionary<string, string> headers)
        {
            if (queryParams != null)
            {
                foreach (var param in queryParams)
                {
                    request.AddQueryParameter(param.Key, param.Value?.ToString());
                }
            }
            AddHeaders(request, headers);
        }

        private void AddHeaders(RestRequest request, Dictionary<string, string> headers)
        {
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    request.AddHeader(header.Key, header.Value);
                }
            }
        }

        public void Dispose()
        {
            GC.SuppressFinalize(this);
        }
    }
}